<script setup lang="js">
import UserWeekPlanAPI from "@/api/weekPlan/user-week-plan";
import moment from "moment/moment";
import SportPlanAPI from "@/api/sportPlan/sport-plan";
import SportDataAPI from "@/api/sport/sport-data";
import PlanSelect from "@/components/my-component/planSelect.vue";
import DateProgress from "@/components/my-component/dateProgress.vue";
import getWeekDays from "@/utils/weekTimeUtil";
import FoodSportDetailPopup from "@/components/my-component/foodSportDetailPopup.vue";
import UserAPI from "@/api/system/user";
const indexLoading = ref(false);
const sportPlan = ref([]);
const showPanel = ref(false);
const searchType = ref("运动");
const searchFood = ref();
const foodList = ref([]);
const datePlan = ref(moment(new Date()).format("YYYY-MM-DD"));
const planSelect = ref();
const weekPlan = ref(0);
const curSportTime=ref(0)
const weekSportTime=ref(0)
const energy=ref(0)
const dateProgress=ref()
const minus=ref(0)
const detailPopup=ref()
onShow(async () => {
  const userInfo=await UserAPI.getProfile()
  if(userInfo.height&&userInfo.weight&&userInfo.age&&userInfo.gender){
    indexLoading.value = true;
    getWeekPlan();
    handleDatePlanConfirm({ value: new Date() });
    weekCalendar(0);
  }else {
    uni.navigateTo({
      url: "/pages/mine/profile/index"
    })
  }
});
function handleClick(e) {
  showPanel.value = !showPanel.value;
}
function handlePlanDel(id, type) {
  wx.showModal({
    title: "提示",
    content: "是否删除？",
    success(res) {
      if (res.confirm) {
        SportPlanAPI.deleteByIds(id).then((res) => {
          uni.showToast({ title: "删除成功", icon: "none" });
          weekCalendar(0)
        });
      }
    },
  });
}
function handleDatePlanConfirm({ value }) {
  indexLoading.value = true;
  datePlan.value = formatDate(new Date(value));
  SportPlanAPI.getPage({ planDate: datePlan.value, pageSize: 999 })
    .then((res) => {
      sportPlan.value = res.list;
      let energyRes = 0;
	  let quantityRes=0;
      res.list.forEach((item) => {
        energyRes += item.energy;
		quantityRes+=parseInt(item.quantity);
      });
      energy.value = energyRes.toFixed(1);
	  curSportTime.value=quantityRes
    })
    .finally(() => {
      indexLoading.value = false;
    });
}
function formatDate(date) {
  let momentDate = moment(date);
  return momentDate.format("YYYY-MM-DD");
}
function cancel() {
  showPanel.value = false;
  handleDatePlanConfirm({ value: new Date() });
  clear();
}
function clear() {
  searchFood.value = "";
  foodList.value = [];
}
function queryFood() {
  console.log(searchFood.value);
}
function search() {
  if (searchFood.value != null && searchFood.value !== "") {
    SportDataAPI.getPage({ sportType: searchFood.value, pageSize: 999 }).then((res) => {
      foodList.value = res.list;
    });
  } else {
    foodList.value = [];
  }
}
const getWeekPlan = () => {
  UserWeekPlanAPI.getFormData().then((res) => {
    if (res != null) {
      weekPlan.value = res.sportTime;
    }
  });
};
function weekCalendar(data){
  minus.value+=data
  let date=new Date(datePlan.value)
  date.setDate(date.getDate()+7*data)
  let dates=getWeekDays(date)
  SportPlanAPI.weekCalendar(dates).then(res=>{
    if (res!=null){
	let quantityRes = 0;
      res.forEach(item=>{
		  quantityRes += parseInt(item.energy);
        if(formatDate(date)===item.oriDate){
          item.isSelected=true
        }
      })
	  weekSportTime.value = quantityRes;
      dateProgress.value.showData(res)
      handleDatePlanConfirm({ value: new Date(date) });
    }
  })
}
</script>

<template>
  <view style="width: 100%; height: var(--status-bar-height)" />
  <view class="flexSpaceBetween">
    <view class="flexSpaceBetween">
      <wd-button type="icon" icon="arrow-left" @click="weekCalendar(-1)"></wd-button>
      <view>{{datePlan}}</view>
    </view>
    <wd-button v-if="minus<0" type="icon" icon="arrow-right" @click="weekCalendar(1)"></wd-button>
  </view>
  <DateProgress ref="dateProgress" :common-color="'#0079fe'" @handleDatePlanConfirm="handleDatePlanConfirm"/>
  <view style="margin-top: 20px;text-align: center">
    <view class="scroll-view-item_H">
      <wd-card>
        <view style="height:270rpx;">
          <view style="padding: 20px 0 0 0">
            <wd-button type="primary" @click="planSelect.handleShow(weekPlan)">
              &nbsp;&nbsp;每周运动目标：{{ weekPlan }}分钟&nbsp;&nbsp;
              <wd-icon name="edit-outline"></wd-icon>
              &nbsp;&nbsp;
            </wd-button>
          </view>

          <wd-loading v-if="indexLoading"></wd-loading>
          <view
            v-else
            style="
                padding: 10px 0 15px 0;
                display: flex;
                justify-content: space-around;
                align-items: center;
              "
          >
		  <view>
		    <view
		      class="sportTitle"
		      :style="weekSportTime > weekPlan ? { color: '#82d44f' } : { color: '#fe9400' }"
		    >
		      {{ weekSportTime }}分钟
		    </view>
		    <view class="sportContent">周时长</view>
		  </view>
            <view>
              <view
                class="sportTitle"
              >
                {{ curSportTime }}分钟
              </view>
              <view class="sportContent">日时长</view>
            </view>
            <view>
              <view class="sportTitle" style="color: #0079fe">{{ energy }}Kcal</view>
              <view class="sportContent">消耗热量</view>
            </view>
          </view>
        </view>
      </wd-card>
    </view>
  </view>
  <wd-status-tip
    v-if="sportPlan == null || sportPlan.length === 0"
    type="search"
    tip="当前搜索无结果"
  />
  <view v-else>
    <view class="sportPlanTitle">运动</view>
    <view class="planContent">
      <wd-card v-for="(item, index) in sportPlan" :key="index">
        <view
          style="display: flex; align-items: center; justify-content: space-between"
          @click="detailPopup.handleDetailShow(null, item)"
          @longpress="handlePlanDel(item.id, 'sport')"
        >
          <view>
            <view style="font-size: 15px; margin: 5px 0 5px 0">
              {{ item.sportType }}
            </view>
            <view style="font-size: 10px; margin: 5px 0 5px 0">
              {{ item.quantity }}分钟
            </view>
          </view>
          <view style="font-weight: bold; color: #409fde">-{{ item.energy }}千卡</view>
        </view>
      </wd-card>
    </view>
  </view>
  <wd-popup
    v-model="showPanel"
    :modal="false"
    position="bottom"
    style="max-height: 85vh"
    @close="showPanel = false"
  >
    <view style="max-height: 70vh; height: 70vh; overflow: auto">
      <wd-row custom-class="detailHead">
        <wd-col :span="6">
          <wd-radio-group v-model="searchType" shape="button" @change="foodList = []">
            <wd-radio :value="'运动'">运动</wd-radio>
          </wd-radio-group>
        </wd-col>
        <wd-col :span="18">
          <wd-search
            v-model="searchFood"
            :maxlength="10"
            @search="search"
            @cancel="cancel"
            @clear="clear"
            @change="queryFood"
          />
        </wd-col>
      </wd-row>
      <wd-status-tip v-if="foodList==null||foodList.length===0" type="search" tip="当前搜索无结果"/>
      <view v-else v-for="(item, index) in foodList" :key="index" @click="detailPopup.handleDetailShow(item)">
        <wd-card :title="item.name">
          <wd-row flex justify="space-between" custom-class="sportCard">
            <wd-col :span="18">
              <view style="font-size: 15px; font-weight: bold">{{ item.sportType }}</view>
            </wd-col>
            <wd-col :span="6">
              <view style="color: #409fde; font-weight: bold">{{ item.caloriesPerHour }}千卡</view>
              <view>每60分钟</view>
            </wd-col>
          </wd-row>
        </wd-card>
      </view>
    </view>
  </wd-popup>
  <FoodSportDetailPopup ref="detailPopup" :searchType="searchType" @weekCalendar="weekCalendar"/>
  <view class="floating-button" @click="handleClick">
    <text>+</text>
  </view>
  <PlanSelect ref="planSelect" :increment="30" :title="'每周运动时常'" @get-plan="getWeekPlan" />

</template>

<style setup lang="scss">
.home {
  padding: 10px 30px 5px 30px;
  :deep(.custom-item) {
    height: 80px !important;
  }
  :deep(.wd-card) {
    margin: 10rpx 0 !important;
  }
}
.scroll-view_H {
  white-space: nowrap;
  width: 100%;
  padding: 10px 20px 5px 20px;
}
.scroll-view-item_H {
  display: inline-block;
  width: 90vw;
  white-space: nowrap;
  text-align: center;
  font-size: 36rpx;
  padding: 10px;
}
.detailHead {
  display: flex;
  align-items: center;
  padding: 10px;
}
.charts-box {
  width: 100%;
  height: 300px;
}
.sportTitle {
  font-size: 15px;
  font-weight: bold;
}
.sportContent {
  font-size: 12px;
}
.sportPlanTitle {
  color: #0079fe;
  padding: 10px 20px 5px 40px;
}
.planContent {
  padding: 10px 20px 5px 20px;
}
.sportCard {
  height: 70px;
  display: flex;
  align-items: center;
}
.floating-button {
  position: fixed;
  bottom: 150px;
  right: 20px;
  width: 60px;
  height: 60px;
  background-color: #0079fe;
  border-radius: 50%;
  display: flex;
  justify-content: center;
  align-items: center;
  color: #fff;
  font-size: 30px;
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.3);
  z-index: 999; /* 确保按钮浮在最前 */
}
.flexSpaceBetween{
  display: flex;
  align-items: center;
  justify-content: space-between
}
</style>
